package com.qf.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.qf.entity.YuYueOrder;
import com.qf.service.YuYueOrderService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * --- 冲 ---
 *
 * @author Biggen
 * @date 2025/5/8
 * @desc
 */
@Slf4j
// XxxxListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public class YuYueOrderExcelListener extends AnalysisEventListener<YuYueOrder> {
    private YuYueOrderService service;

    /**
     * 每隔5条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<YuYueOrder> cachedDataList = new ArrayList<>(  );

    public YuYueOrderExcelListener(YuYueOrderService service) {
        this.service = service;
    }

    @Override
    public void invoke(YuYueOrder data, AnalysisContext context) {
        log.info("解析到一条数据:{}", data);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去数据库保存
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList.clear();
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成");
    }

    /**
     * 添加到数据库
     */
    private void saveData() {
        if (!cachedDataList.isEmpty()){
        log.info("{}条数据，开始保存数据", cachedDataList.size());
        service.insertBatch(cachedDataList);
        log.info("存储数据库完成！");
        cachedDataList.clear();
        }
    }
}
